package {

import flash.display.*;
import flash.net.*;
import flash.events.*;
import flash.filters.*;

import com.whirled.*;

[SWF(width="174", height="174")]
public class Album extends Sprite
{
    public function Album ()
    {
        _ctrl = new ToyControl(this);

        _ctrl.addEventListener(ControlEvent.MUSIC_ID3, onMusic);
        _ctrl.addEventListener(ControlEvent.MUSIC_STOPPED, function (... _) :void {
            setCover(null);
        });

        onMusic();
    }

    protected function setCover (cover :DisplayObject) :void
    {
        if (_cover != null) {
            removeChild(_cover);
        }

        _cover = (cover != null) ? cover : new DEFAULT_COVER();
        addChild(_cover);
    }

    protected function onMusic (..._) :void
    {
        var tags :Object = _ctrl.getMusicId3();

        if (tags == null || !("artist" in tags) || !("songName" in tags)) {
            setCover(null);
            return;
        }

        var loader :URLLoader = new URLLoader();
        var request :URLRequest = new URLRequest();

        var query :URLVariables = new URLVariables();
        query.method = "track.getinfo";
        query.api_key = "b25b959554ed76058ac220b7b2e0a026";
        query.artist = tags.artist;
        query.track = tags.songName;

        request.url = "http://ws.audioscrobbler.com/2.0/";
        request.data = query;

        loader.addEventListener(Event.COMPLETE, function (..._) :void {
            var lfm :XML = new XML(loader.data);

            var coverURL :String = lfm.track.album.image.(attribute("size") == "large");
            var infoURL :String = lfm.track.url;

            if (coverURL) {
                var cover :Loader = new Loader();
                cover.load(new URLRequest(coverURL));

                if (infoURL) {
                    cover.addEventListener(MouseEvent.CLICK, function (... _) :void {
                        flash.net.navigateToURL(new URLRequest(infoURL));
                    });
                }
                cover.addEventListener(MouseEvent.ROLL_OVER, function (... _) :void {
                    cover.filters = [ new GlowFilter(0xff0000, 50, 20, 20, 2) ];
                });
                cover.addEventListener(MouseEvent.ROLL_OUT, function (... _) :void {
                    cover.filters = null;
                });
                setCover(cover);

            } else {
                setCover(null);
            }
        });

        loader.load(request);
    }

    [Embed(source="album.png")]
    protected static const DEFAULT_COVER :Class;

    protected var _cover :DisplayObject;
    protected var _ctrl :ToyControl;
}
}
